package com.ysd.lis.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysd.common.Result;
import com.ysd.common.dto.ColumnAndCommentDto;
import com.ysd.common.dto.ColumnValueDto;
import com.ysd.common.dto.ColumnValueDto2;
import com.ysd.lis.dto.EditTableTodoParam;
import com.ysd.lis.dto.EditTableTodoParam2;
import com.ysd.lis.entity.SysBasDictDetail;
import com.ysd.lis.entity.SysBasDictTable;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.mapper.sys.SysBasDictTableMapper;
import com.ysd.lis.request.CommonPageDto;
import com.ysd.lis.service.SysBasDictTableService;
import com.ysd.util.CodeRoleUtils;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import com.ysd.util.UniqueIdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * cold_chain.t_user 服务实现类
 * </p>
 *
 * @author peng
 * @since 2021-10-08
 */
@Service
@Slf4j
public class SysBasDictTableServiceImpl extends ServiceImpl<SysBasDictTableMapper, SysBasDictTable> implements SysBasDictTableService {
   @Autowired
   SysBasDictTableMapper sysBasDictTableMapper;
    @Override
    public Result findDictTablePageList(CommonPageDto pageParam) {
        Page<SysBasDictTable> page = new Page<>();
        page.setCurrent(pageParam.getPageIndex());
        page.setSize(pageParam.getPageSize());
        LambdaQueryWrapper<SysBasDictTable> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysBasDictTable::getDelFlag, 0);
        if (StringUtils.isNotBlank(pageParam.getSeachValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(SysBasDictTable::getName, pageParam.getSeachValue())
                    .or().like(SysBasDictTable::getCode, pageParam.getSeachValue()));
        }
        lambdaQueryWrapper.orderByAsc(SysBasDictTable::getSx);
        Page<SysBasDictTable> tablePage = sysBasDictTableMapper.selectPage(page, lambdaQueryWrapper);
        return Result.succ(1, "查询成功", tablePage);
    }

    @Override
    public Result addDictTable(SysBasDictTable table) {
        int insert = sysBasDictTableMapper.insert(table);
        if(insert>0){
            return Result.succ(1,"添加成功",table);
        }else {
            return Result.fail(400,"添加失败","");
        }
    }

    @Override
    public Result editDictTable(SysBasDictTable table) {
        int updateById = sysBasDictTableMapper.updateById(table);
        if(updateById>0){
            return Result.succ(1,"提交成功",table);
        }else {
            return Result.fail(400,"修改失败","");
        }
    }

    @Override
    public Result deleteDictTable(SysBasDictTable table) {
        int deleteById = sysBasDictTableMapper.deleteById(table.getId());
        if(deleteById>0){
            return Result.succ(1, "删除成功", "");
        }else {
            return Result.fail(400, "删除失败", "");
        }
    }

    @Override
    public Result getTableColumns(CommonPageDto pageParam) {
        List<ColumnAndCommentDto> ColumnAndComments = sysBasDictTableMapper.findColumnsByTableName(pageParam.getTableName());
        return Result.succ(1, "查询成功！", ColumnAndComments);
    }

    @Override
    public Result addTableData(EditTableTodoParam2 editTableTodoParam) {
        List<ColumnValueDto> list = builderAddBaseColumn();
        List<ColumnValueDto2> valueDtoList = editTableTodoParam.getList();
        if (CollectionUtils.isNotEmpty(valueDtoList)) {
            //查看是否有标识字段，如果有标识字段则按照规则生成值
            List<ColumnValueDto2> collect = valueDtoList.stream().filter(a -> StringUtils.isNotBlank(a.getClassify())&&a.getClassify().equals("1")).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(collect)){
                for(ColumnValueDto2 detail : collect){
                    //取前缀
                    String prefixType = detail.getPrefixType();
                    String prefix = detail.getPrefix();
                    String prefixText = CodeRoleUtils.getFixRoleText(prefixType,prefix,null);
                    //取中缀
                    String infixType = detail.getInfixType();
                    String infix = detail.getInfix();
                    String infixText = CodeRoleUtils.getFixRoleText(infixType, infix,null);
                    //取后缀
                    String suffixType = detail.getSuffixType();
                    String suffix = detail.getSuffix();
                    Integer suffLeth = 4;
                    if(suffixType.equals("seq")){
                        suffLeth = Integer.valueOf(suffix);
                    }

                    Integer integer =   (int) (Math.pow(10,suffLeth))+1 ;
//                    QueryWrapper<SysBasDictDetail> queryWrapperApp = new QueryWrapper<>();
//                    queryWrapperApp.select("max(SUBSTR(VALUE, "+suffLeth*-1+", "+suffLeth+")) as VALUE")
//                            .like("VALUE",prefixText+infixText)
//                            .eq("PID",detail.getPid());
//                    SysBasDictDetail or = sysBasDictDetailMapper.selectOne(queryWrapperApp);
                   String value =  sysBasDictTableMapper.selectColumnValueByRuleTodoTable(editTableTodoParam.getTableName(),detail.getColumn(),suffLeth,prefixText+infixText);
                    if(null == value){
                        detail.setValue(prefixText+infixText+ String.valueOf(integer).substring(1));
                    }else{
                        detail.setValue(prefixText+infixText+String.valueOf(Integer.valueOf(value)+integer).substring(1));
                    }

                }
            }

            for(ColumnValueDto2 dto : valueDtoList){
                Optional<ColumnValueDto> first = list.stream().filter(a -> a.getColumn().equals(dto.getColumn())).findFirst();
                if(!first.isPresent()){

                    list.add(new ColumnValueDto(dto.getColumn(), dto.getValue(), dto.getColumnType())  );
                }
            }
        }
        int i = sysBasDictTableMapper.insertTransmitTodoTable(editTableTodoParam.getTableName(), list);
        return Result.succ(1, "添加成功！", null);
    }

    @Override
    public Result deleteTableData(CommonPageDto pageParam) {
        String tableName = pageParam.getTableName();
        Map<String, Object> map = pageParam.getMap();
        String id = (String) map.get("ID");
        boolean b = sysBasDictTableMapper.deleteDynamicTableData(tableName, id);
        if (b) {
            return Result.succ(1, "删除成功！", null);
        } else {
            return Result.fail("删除失败！");
        }
    }

    @Override
    public Result findAllTableList(String seachValue) {
        List<Map<String, String>> tableNames;
        if(ToolsUtils.isEmpty(seachValue)){
            tableNames = sysBasDictTableMapper.findTableNames("");
        }else {
            tableNames = sysBasDictTableMapper.findTableNames(seachValue);

        }
        return Result.succ(1, "查询成功！", tableNames);
    }

    @Override
    public Result editTableData(EditTableTodoParam editTableTodoParam) {
        if (CollectionUtils.isNotEmpty(editTableTodoParam.getList()) ) {
            List<ColumnValueDto> collect = editTableTodoParam.getList().stream().filter(a -> StringUtils.isNotBlank(a.getValue())).collect(Collectors.toList());
            int i = sysBasDictTableMapper.updateTransmitTodoTable(editTableTodoParam.getTableName(), collect);
            if(i>0){
                return Result.succ(1, "编辑成功！", i);
            }else {
                return Result.fail( "编辑失败！");
            }
        }else {
            return Result.fail( "编辑失败！");
        }
    }

    /**
     * 构建添加默认插入字段
     * @return
     */
    public List<ColumnValueDto> builderAddBaseColumn() {
        SysUser user = RedisUserManager.getUser();
        List<ColumnValueDto> list = new ArrayList<>();
        list.add(new ColumnValueDto("ID", IdUtil.getSnowflake().nextId() + "", "NVARCHAR2"));
        list.add(new ColumnValueDto("CREATOR", user.getUsername(), "NVARCHAR2"));
        list.add(new ColumnValueDto("EDITOR", user.getUsername(), "NVARCHAR2"));
        list.add(new ColumnValueDto("CREATE_TIME", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"), "DATE"));
        list.add(new ColumnValueDto("EDIT_TIME", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"), "DATE"));
        list.add(new ColumnValueDto("DEL_FLAG", "0", "NVARCHAR2"));
        return list;
    }

}
